package xcar_parser

import (
	"crawler/concurrent_crawler/engine"
	"crawler/concurrent_crawler/model"
	"fmt"
	"regexp"
	"strconv"
)

//<title>【坦克3002021款越野版 2.0T 挑战者】报价_图片_参数-爱卡汽车</title>
//<img class="color_car_img_new" src="//img1.xcarimg.com/b344/s13352/m_20201222092659886902084907385.jpg-280x210.jpg"
//<li><span>车身尺寸:</span><em>4760×1930×1927mm</em></li>
//<li class="bd_l"><span>工信部油耗:</span><em>9.3L/100km</em></li>
//<li><span>变 速 箱:</span><em>8挡自动</em></li>
//<li class="bd_l"><span>发 动 机:</span><em>167kW(2.0L涡轮增压)</em></li>
//<li><span>驱动方式:</span><em>前置四驱</em></li>
//<li class="bd_l"><span>排　　量:</span><em>2.0L</em></li>
//<td class="w148 ">最高车速(km/h)</td>
//<td class="w237">-</td>
//</tr><tr>                                   <td class="w148 bdl">0-100加速时间(s)</td>
//<td class="w237">9.5</td>

var nameRe = regexp.MustCompile(`<title>【(.*)】报价_图片_参数-爱卡汽车</title>`)
var carImageRe = regexp.MustCompile(`<img class="color_car_img_new" src="([^"]+)"`)
var sizeRe = regexp.MustCompile(`<li.*车身尺寸.*<em>(\d+[^\d]\d+[^\d]\d+mm)`)
var fuelRe = regexp.MustCompile(`<li.*工信部油耗.*<em>(\d+\.\d+)L/100km`)
var transmissionRe = regexp.MustCompile(`<li.*变\s*速\s*箱.*<em>(.+)</em>`)
var engineRe = regexp.MustCompile(`发\s*动\s*机.*\s*.*<.*>(\d+kW[^<]*)<`)
var displacementRe = regexp.MustCompile(`<li.*排.*量.*(\d+\.\d+)L`)
var maxSpeedRe = regexp.MustCompile(`<td.*最高车速\(km/h\).*\s*<td[^>]*>(\d+)</td>`)
var accelRe = regexp.MustCompile(`<td.*0-100加速时间\(s\).*\s*<td[^>]*>([\d.]+)</td>`)
var urlRe = regexp.MustCompile(`http://newcar.xcar.com.cn/(m\d+)/`)

//<a href="/m58052/baojia/" target="_blank" onclick="clicklog(124663);">19.58</a>
var priceReTmpl = `<a href="/%s/baojia/".*>(\d+\.\d+)</a>`

func ParseCarDetail(contents []byte, url string) engine.ParseResult {
	id := extractString([]byte(url), urlRe)

	car := model.Car{
		Name:         extractString(contents, nameRe),
		ImageURL:     "http:" + extractString(contents, carImageRe),
		Size:         extractString(contents, sizeRe),
		Fuel:         extractFloat(contents, fuelRe),
		Transmission: extractString(contents, transmissionRe),
		Engine:       extractString(contents, engineRe),
		Displacement: extractFloat(contents, displacementRe),
		MaxSpeed:     extractFloat(contents, maxSpeedRe),
		Acceleration: extractFloat(contents, accelRe),
	}
	priceRe, err := regexp.Compile(
		fmt.Sprintf(priceReTmpl, regexp.QuoteMeta(id)))
	if err == nil {
		car.Price = extractFloat(contents, priceRe)
	}

	result := engine.ParseResult{
		Items: []engine.Item{
			{
				Url:     url,
				Type:    "xcar",
				Id:      id,
				Payload: car,
			},
		},
	}
	return result
}

func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents)

	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}
}

func extractFloat(contents []byte, re *regexp.Regexp) float64 {
	f, err := strconv.ParseFloat(extractString(contents, re), 64)
	if err != nil {
		return 0
	}
	return f
}
